package com.hepinghospital.user.ui.activity.eyecheck;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.ui.dialog.UpdateDialog;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.observer.BaseObserver;
import com.rest.response.BaseJsonResponse;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.UtilList;

/**
 * 眼科检查记录列表
 *
 * @time 2021/1/6 9:30
 */

public class EyeBookListActivity extends BaseActivity {


    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.cl_empty)
    ConstraintLayout clEmpty;

    int current = 1, totalPage;
    Boolean isLoadMore = true;//能不能继续加载更多
    MyAdapter adapter;

    List<BaseJsonResponse.Records> mCheckList = new ArrayList<>();

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_base_list;
    }

    @Override
    protected void initViews() {
        tvTitle.setText("检查记录");
//        btnAdd.setVisibility( View.VISIBLE );
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        adapter = new MyAdapter();
        refreshLayout.setPrimaryColors(0xffffffff, 0xff55B8A9);

        recyclerView.setAdapter(adapter);
        refreshLayout.setEnableLoadMore(true);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NotNull RefreshLayout refreshlayout) {
                refreshLayout.finishRefresh();
                refreshLayout.setNoMoreData(false);//复原状态
                current = 1;
                queryCheckList();
            }
        });

        //加载更多
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {

                if (current > totalPage) {
                    refreshLayout.finishLoadMore();
                    refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                    //refreshLayout.setNoMoreData(false);
                    ToastUtil.showToast(mContext, "数据全部加载完毕");
                } else {
                    queryCheckListMore();

                }
            }
        });

    }

    @Override
    protected void initData() {
//        patientId = getIntent().getStringExtra( "patientId" );
        queryCheckList();
    }


    /**
     * 查询挂号记录
     *
     * @time 2021/1/7 13:53
     */
    private void queryCheckList() {
        RestProxy.getInstance().queryCheckList(current + "", "10", new BaseObserver<BaseJsonResponse>() {
            @Override
            public void onSuccess(BaseJsonResponse baseJsonResponse) {
                try {
                    Log.e("挂号次数---", baseJsonResponse.records.size() + "");
                    totalPage = Integer.parseInt(baseJsonResponse.pages);
                    List<BaseJsonResponse.Records> records = baseJsonResponse.records;
                    if (!UtilList.isEmpty(records)) {
                        refreshLayout.setVisibility(View.VISIBLE);
                        clEmpty.setVisibility(View.GONE);
                        mCheckList.clear();
                        mCheckList.addAll(baseJsonResponse.records);
                        adapter.notifyDataSetChanged();
                    } else {
                        refreshLayout.setVisibility(View.GONE);
                        clEmpty.setVisibility(View.VISIBLE);
                    }
                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
                refreshLayout.finishRefresh(false);
            }

            @Override
            public void onComplete() {
                refreshLayout.finishRefresh(true);
            }
        });
    }

    private void queryCheckListMore() {
        current += 1;
        RestProxy.getInstance().queryCheckList(current + "", "10", new Observer<BaseJsonResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(BaseJsonResponse baseJsonResponse) {
                try {
                    Log.e("次数更多---", baseJsonResponse.records.size() + "");
                    List<BaseJsonResponse.Records> records = baseJsonResponse.records;
                    if (!UtilList.isEmpty(records)) {
                        mCheckList.addAll(baseJsonResponse.records);
                        adapter.notifyDataSetChanged();
                        refreshLayout.finishLoadMore();

                    }


                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
                refreshLayout.finishLoadMore();
            }

            @Override
            public void onComplete() {
                refreshLayout.finishLoadMore();
            }
        });
    }


    /**
     * 取消眼科医院预约
     *
     * @time 2020/8/24 10:19
     */
    private void delPrescription(String checkFormDetailId, int position) {
        RestProxy.getInstance().cancelCheck(checkFormDetailId, new BaseObserver<String>() {
            @Override
            public void onSuccess(String prescriptionResponse) {
                mCheckList.remove(position);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

        });
    }

    class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {


        @NotNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            Context context = parent.getContext();
            View view = LayoutInflater.from(context)
                    .inflate(R.layout.item_eye_book_list, parent, false);
            return new ViewHolder(view);

        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NotNull RecyclerView.ViewHolder holder, final int position) {
            final ViewHolder mHolder = (ViewHolder) holder;
            mHolder.tvEyeType.setText(mCheckList.get(position).checkItem);
            mHolder.tvEyeBookNum.setText(mCheckList.get(position).applyFormId);
            mHolder.tvPatientName.setText(mCheckList.get(position).patientName);
            mHolder.tvEyeLeft.setText(mCheckList.get(position).checkSeries);
            mHolder.tvLookTime.setText(mCheckList.get(position).checkTime);
            mHolder.tvEyeHospitalName.setText(mCheckList.get(position).hosName);
            String cancelFlag = mCheckList.get(position).cancelFlag;
            if ("0".equals(cancelFlag)) {
                mHolder.btnCancel.setBackground(ContextCompat.getDrawable(mContext, R.drawable.shape_gray_25dp));
            } else {
                mHolder.btnCancel.setBackground(ContextCompat.getDrawable(mContext, R.drawable.item_bg_light_green_button));
            }
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String checkItemCode = mCheckList.get(position).checkItemCode;
                    //101 眼底照相检查 102 眼压检查 103 眼前节照相检查 104 视力检查 105 屈光检查
                    if ("102".equals(checkItemCode)) {
                        Bundle bundle = new Bundle();
                        bundle.putString("checkDetailId", mCheckList.get(position).checkFormDetailId);
                        startActivity(EyeYaDetailActivity.class, bundle);
                    } else if ("105".equals(checkItemCode)) {
                        Bundle bundle = new Bundle();
                        bundle.putString("checkDetailId", mCheckList.get(position).checkFormDetailId);
                        startActivity(EyeDiopterDetailActivity.class, bundle);
                    } else if ("104".equals(checkItemCode)) {
                        Bundle bundle = new Bundle();
                        bundle.putString("checkDetailId", mCheckList.get(position).checkFormDetailId);
                        startActivity(EyeVisionDetailActivity.class, bundle);
                    } else {
                        Bundle bundle = new Bundle();
                        Log.e("checkDetailId---", mCheckList.get(position).checkFormDetailId);
                        bundle.putString("checkDetailId", mCheckList.get(position).checkFormDetailId);
                        startActivity(EyeDiDetailActivity.class, bundle);
                    }

                }
            });
            mHolder.btnCancel.setOnClickListener(v -> {
                if ("1".equals(cancelFlag)) {
                    UpdateDialog mUpdateDialog = UpdateDialog.newInstance(5, true);
                    mUpdateDialog.show(getSupportFragmentManager(), "mUpdateDialog");
                    mUpdateDialog.setmListener(new UpdateDialog.OnItemClickListener() {

                        @Override
                        public void onConfirm() {
                            delPrescription(mCheckList.get(position).checkFormDetailId, position);
                        }

                        @Override
                        public void onCancel() {

                        }
                    });
                } else {
                    ToastUtil.showToast(mContext, "当前预约不可取消");
                }


            });

        }

        @Override
        public int getItemCount() {
            return mCheckList.size();
        }


        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.tv_eye_type)
            TextView tvEyeType;
            @BindView(R.id.tv_eye_book_num)
            TextView tvEyeBookNum;
            @BindView(R.id.tv_patient_name)
            TextView tvPatientName;
            @BindView(R.id.tv_eye_left)
            TextView tvEyeLeft;
            @BindView(R.id.tv_look_time)
            TextView tvLookTime;
            @BindView(R.id.tv_eye_hospital_name)
            TextView tvEyeHospitalName;
            @BindView(R.id.btn_cancel)
            TextView btnCancel;

            ViewHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }

    }
}
